import {
  Button,
  Form,
  FormItem,
  Input,
  Modal,
  RadioGroup,
  Space,
  Tag,
  Textarea
} from 'ant-design-vue'
import { omitBy } from 'lodash-unified'
import { defineComponent, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { dictApi } from '@/apis'
import { ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { TableOptions, usePageHeight, useTableRef } from '@/hooks'
import { dictToOptions } from '@/utils'

import { useOperation, useToolbar } from './hooks'
import type { DictTypeFormType } from './types'

export default defineComponent({
  name: 'DictTypeView',
  setup() {
    const statusOptions = ref([] as OptionItem[])
    const selectedIds = ref(new Set<string>())
    const tableConfig = ref({
      border: true,
      loading: false,
      showOverflow: true,
      height: 'auto',
      toolbarConfig: {
        refresh: true,
        zoom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      formConfig: {
        items: [
          {
            field: 'dictName',
            title: '字典名称',
            itemRender: {
              name: TABLE_ITEM_RENDER.AInput,
              props: {
                placeholder: '请输入字典名称'
              }
            }
          },
          {
            field: 'dictType',
            title: '字典类型',
            itemRender: {
              name: TABLE_ITEM_RENDER.AInput,
              props: {
                placeholder: '请输入字典类型'
              }
            }
          },
          {
            field: 'status',
            title: '状态',
            itemRender: {
              name: TABLE_ITEM_RENDER.ASelect,
              props: {
                placeholder: '岗位状态'
              }
            }
          },
          {
            itemRender: {
              name: TABLE_RENDERER.FormItemBtns
            }
          }
        ]
      },
      columns: [
        { type: 'checkbox', width: 50 },
        {
          field: 'dictId',
          title: '字典编号'
        },
        {
          field: 'dictName',
          title: '字典名称'
        },
        {
          field: 'dictType',
          title: '字典类型',
          slots: {
            default: 'dict_type'
          }
        },
        {
          field: 'status',
          title: '状态',
          slots: {
            default: 'status'
          }
        },
        {
          field: 'remark',
          title: '备注'
        },
        {
          field: 'createTime',
          title: '创建时间',
          formatter: TABLE_FORMAT.Date
        },
        {
          title: '操作',
          slots: {
            default: 'operation'
          }
        }
      ],
      pagerConfig: {
        pageSize: 15
      },
      proxyConfig: {
        seq: true,
        form: true,
        props: {
          result: 'list',
          total: 'total'
        },
        ajax: {
          query: async ({ page, form }) => {
            form = omitBy(form, value => {
              return value === null
            })

            const data = await dictApi.getDictTypePage({
              pageSize: page.pageSize,
              pageNum: page.currentPage,
              ...form
            })
            return data
          }
        }
      },
      onCheckboxChange({ checked, row }) {
        checked
          ? selectedIds.value.add(row.dictId)
          : selectedIds.value.delete(row.dictId)
      }
    } as TableOptions)

    const router = useRouter()
    const tableRefHook = useTableRef(tableConfig)
    const toolbarHook = useToolbar({
      selectedIds,
      tableRefHook
    })
    const operationHook = useOperation({ tableRefHook })
    const { pageHeightPx } = usePageHeight()

    function handleViewData(item: any) {
      router.push({
        name: 'DictDataView',
        params: {
          id: item.dictId
        }
      })
    }

    async function init() {
      const [dictStatus] = await Promise.all([
        dictApi.getDictDataList('sys_normal_disable')
      ])

      statusOptions.value = dictToOptions(dictStatus)

      tableRefHook.updateFormItem({
        field: 'status',
        key: 'itemRender.props.options',
        value: statusOptions.value
      })
    }

    onMounted(() => {
      init()
    })

    return {
      statusOptions,
      selectedIds,
      tableRef: tableRefHook.tableRef,
      tableConfig,
      pageHeightPx,
      handleViewData,
      ...toolbarHook,
      ...operationHook
    }
  },
  render() {
    const renderForm = (type: DictTypeFormType) => {
      const formRef = type === 'add' ? this.addFormRef : this.editFormRef
      const formModel = type === 'add' ? this.addFormModel : this.editFormModel

      return (
        <Modal
          title={type === 'add' ? '添加字典类型' : '修改字典类型'}
          visible={type === 'add' ? this.showAdd : this.showEdit}
          confirmLoading={type === 'add' ? this.addLoading : this.editLoading}
          onOk={type === 'add' ? this.handleAdd : this.handleEdit}
          onCancel={type === 'add' ? this.handleCloseAdd : this.handleCloseEdit}
          destroyOnClose
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label={'字典名称'} {...formRef.validateInfos['dictName']}>
              <Input v-model:value={formModel.dictName} />
            </FormItem>
            <FormItem label={'字典类型'} {...formRef.validateInfos['dictType']}>
              <Input v-model:value={formModel.dictType} />
            </FormItem>
            <FormItem label={'状态'}>
              <RadioGroup
                v-model:value={formModel.status}
                options={this.statusOptions}
              ></RadioGroup>
            </FormItem>
            <FormItem label={'备注'}>
              <Textarea
                v-model:value={formModel.remark}
                placeholder="请输入内容"
              />
            </FormItem>
          </Form>
        </Modal>
      )
    }

    return (
      <div
        style={{
          height: this.pageHeightPx
        }}
      >
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbar_buttons: () => (
              <Space>
                <Button
                  v-permission="system:dict:add"
                  type={'primary'}
                  ghost
                  onClick={this.handleShowAdd}
                >
                  新增
                </Button>
                <Button
                  v-permission="system:dict:remove"
                  danger
                  ghost
                  disabled={this.selectedIds.size === 0}
                  onClick={this.handleDeleteList}
                >
                  删除
                </Button>
                <Button
                  v-permission="system:dict:export"
                  type={'primary'}
                  ghost
                  disabled={!this.canExport}
                  onClick={this.handleExport}
                >
                  导出
                </Button>
              </Space>
            ),
            dict_type: ({ row }) => (
              <Button
                size={'small'}
                type={'link'}
                onClick={() => this.handleViewData(row)}
              >
                {row.dictType}
              </Button>
            ),
            status: ({ row }) =>
              row.status === '1' ? (
                <Tag color={'red'}>停用</Tag>
              ) : (
                <Tag color={'blue'}>正常</Tag>
              ),
            operation: ({ row }) => (
              <Space size={'small'}>
                <Button
                  v-permission="system:dict:edit"
                  type={'link'}
                  size={'small'}
                  onClick={() => this.handleShowEdit(row)}
                >
                  修改
                </Button>
                <Button
                  v-permission="system:dict:remove"
                  type={'link'}
                  size={'small'}
                  onClick={() => this.handleDelete(row.dictId)}
                >
                  删除
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        {/* 新增弹窗 */}
        {renderForm('add')}
        {/* 修改弹窗 */}
        {renderForm('edit')}
      </div>
    )
  }
})
